package com.yamawa.app;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {
    @Bind(R.id.act_main_webView)
    WebView webView;
    @Bind(R.id.act_main_pro)
    ProgressBar progressBar;
    @Bind(R.id.loadlayout)
    LoadLayout loadLayout;
    private WebSettings webSetting;
    private String url = "http://211.149.169.201/index.php/index/index/yamawa";
    private String webContent;
    private boolean fullScreen = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);


        if (fullScreen) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
        }

        webSetting = webView.getSettings();
        webView.getSettings().setAllowContentAccess(true);
//        webView.getSettings().setAppCacheEnabled(true);
        //支持javascript
        webSetting.setJavaScriptEnabled(true);
        // 设置可以支持缩放
        webSetting.setSupportZoom(false);
        //扩大比例的缩放
        webSetting.setUseWideViewPort(true);
        //建立缩放控制
        webSetting.setBuiltInZoomControls(true);
        //缩放按钮显示
        webSetting.setDisplayZoomControls(false);
        //自适应屏幕
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSetting.setLoadWithOverviewMode(true);
//        webSetting.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

        webView.getSettings().setDomStorageEnabled(true);
//        webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, new android.graphics.Paint());

        webView.loadUrl(url);

        initListener();

        loadLayout.setStatus(LoadLayout.TYPE_LOADING);
    }

    public void initListener() {
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    progressBar.setVisibility(View.GONE);
                    loadLayout.setStatus(LoadLayout.TYPE_SUCCESS);
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                }
            }
        });
        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Message msg = handler.obtainMessage();//发送通知，加入线程
                msg.what = 201;//下载
                msg.obj = url;
                handler.sendMessage(msg);//通知发送！
            }
        });
        //如果不设置WebViewClient，请求会跳转系统浏览器
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //该方法在Build.VERSION_CODES.LOLLIPOP以前有效，从Build.VERSION_CODES.LOLLIPOP起，建议使用shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                if (!TxtUtil.isEmpty(url)) {
                    view.loadUrl(url);
                    return true;
                }
                return true;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                String url = request.getUrl().toString();
                if (!TxtUtil.isEmpty(url)) {
                    view.loadUrl(url);
                    return true;
                }
                return true;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                view.stopLoading();
                Message msg = handler.obtainMessage();//发送通知，加入线程
                msg.what = -1;//通知加载自定义404页面
                handler.sendMessage(msg);//通知发送！
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                view.stopLoading();
                Message msg = handler.obtainMessage();//发送通知，加入线程
                msg.what = -1;//通知加载自定义404页面
                handler.sendMessage(msg);//通知发送！
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();  //接受所有证书
            }
        });

        loadLayout.setReloadListener(new LoadLayout.OnReloadListener() {
            @Override
            public void onReload() {
                webView.reload();
            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    progressBar.setVisibility(View.GONE);
//                    loadLayout.setStatus(LoadLayout.TYPE_ERROR);
                    break;
                case 200:
                    Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
                    intent.putExtra("url", url);
                    startActivity(intent);
                    break;
                case 201:
                    String url = msg.obj.toString();
                    openBrowser(MainActivity.this, url);
                    break;
            }
        }
    };

    /**
     * 调用第三方浏览器打开
     *
     * @param context
     * @param url     要浏览的资源地址
     */
    public static void openBrowser(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            // 打印Log   ComponentName到底是什么
            Log.d("test", "componentName = " + componentName.getClassName());
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {
            Toast.makeText(context.getApplicationContext(), "请下载浏览器", Toast.LENGTH_SHORT).show();
        }
    }

    private long exitTime = 0;

    // 设置回退
    // 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (webView.canGoBack()) {
                // 返回上一页面
                webView.goBack(); // goBack()表示返回WebView的上一页面
            } else {
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {
                    finish();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class TopBarClickedListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
//                case R.id.top_bar_back:
//                    if (webView.canGoBack()) {
//                        webView.goBack(); // goBack()表示返回WebView的上一页面
//                    } else {
//                        finish();
//                    }
//                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onPause() {
        hideKeyboard();
        super.onPause();
    }

    private void hideKeyboard() {
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(),
                    0);
        }
    }
}
